package com.heima.media.listener;

import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 添加监听器
 */
@Service
public class PublishArticleListener {
    @Autowired
    private RedissonClient client;
    @Autowired
    private IAuditService auditService;

    @PostConstruct //实例化执行该方法
    public void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //监听redis队列

                RBlockingQueue<Object> queue = client.getBlockingQueue("publish_article");
                RDelayedQueue<Object> delayedQueue = client.getDelayedQueue(queue);
                //发送延迟消息,激活连接 参数 1 消息   2.延迟时间  3 时间单位
                delayedQueue.offer("init", 1, TimeUnit.MILLISECONDS);
                while (true) {
                    try {
                        Object msg = queue.poll(1, TimeUnit.MILLISECONDS);
                        if (msg != null && !msg.equals("init")) {
                            System.out.println(Thread.currentThread().getName() + "接收到消息:" + msg + new Date());
                            //重新发布文章
                            auditService.autoAudit((WmNews) msg);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }

}
